<template>
  <div class="roles-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2>角色管理</h2>
      <el-button type="primary" @click="handleAdd" icon="el-icon-plus">新增角色</el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-box">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入角色名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
          <el-button @click="handleReset" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 角色列表表格 -->
    <div class="table-container">
      <el-table
        v-loading="tableLoading"
        :data="roleList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" min-width="120" />
        <el-table-column prop="description" label="角色描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="权限数量" width="100">
          <template slot-scope="scope">
            <el-tag size="mini">{{ scope.row.permissionCount || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用户数量" width="100">
          <template slot-scope="scope">
            <el-tag size="mini" type="success">{{ scope.row.userCount || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)" icon="el-icon-edit">编辑</el-button>
            <el-button size="mini" type="info" @click="handlePermissions(scope.row)" icon="el-icon-key">权限</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedRoles.length > 0">
        <el-button size="small" type="danger" @click="handleBatchDelete">批量删除</el-button>
        <span class="selected-info">已选择 {{ selectedRoles.length }} 项</span>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </div>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 权限管理对话框 -->
    <el-dialog
      title="权限管理"
      :visible.sync="permissionDialogVisible"
      width="800px"
      @close="handlePermissionDialogClose"
    >
      <div class="permission-header">
        <h4>为角色 "{{ currentRole.name }}" 分配权限</h4>
      </div>
      <el-tree
        ref="permissionTree"
        :data="permissionList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-checked-keys="rolePermissions"
        class="permission-tree"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePermissionSubmit" :loading="permissionLoading">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoleListWithPagination,
  createRole,
  updateRole,
  deleteRole,
  batchDeleteRoles,
  getPermissionList,
  getRolePermissions,
  updateRolePermissions
} from '@/api/role'

export default {
  name: 'Roles',
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: ''
      },
      // 表格数据
      roleList: [],
      tableLoading: false,
      selectedRoles: [],
      // 分页
      pagination: {
        page: 1,
        pageSize: 20,
        total: 0
      },
      // 对话框
      dialogVisible: false,
      dialogTitle: '新增角色',
      submitLoading: false,
      roleForm: {
        name: '',
        description: ''
      },
      roleRules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        description: [
          { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
        ]
      },
      // 权限管理
      permissionDialogVisible: false,
      permissionLoading: false,
      currentRole: {},
      permissionList: [],
      rolePermissions: [],
      treeProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  computed: {
    isEdit() {
      return this.dialogTitle === '编辑角色'
    }
  },
  mounted() {
    console.log('Roles 组件已挂载')
    this.getRoleList()
    // 暂时注释掉权限列表获取，避免 404 错误
    // this.getPermissionList()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      this.tableLoading = true
      try {
        const params = {
          pageNumber: this.pagination.page,
          pageSize: this.pagination.pageSize,
          ...this.searchForm
        }
        const response = await getRoleListWithPagination(params)
        
        // 根据后端返回的数据结构调整
        this.roleList = response.data || []
        this.pagination.total = response.totalCount || 0
      } catch (error) {
        this.$message.error('获取角色列表失败')
        console.error('获取角色列表错误:', error)
      } finally {
        this.tableLoading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.page = 1
      this.getRoleList()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        name: ''
      }
      this.pagination.page = 1
      this.getRoleList()
    },

    // 分页
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.page = 1
      this.getRoleList()
    },

    handleCurrentChange(val) {
      this.pagination.page = val
      this.getRoleList()
    },

    // 选择变化
    handleSelectionChange(selection) {
      this.selectedRoles = selection
    },

    // 新增角色
    handleAdd() {
      this.dialogTitle = '新增角色'
      this.roleForm = {
        name: '',
        description: ''
      }
      this.dialogVisible = true
    },

    // 编辑角色
    handleEdit(row) {
      this.dialogTitle = '编辑角色'
      this.roleForm = {
        id: row.id,
        name: row.name,
        description: row.description
      }
      this.dialogVisible = true
    },

    // 删除角色
    handleDelete(row) {
      this.$confirm(`确定要删除角色 "${row.name}" 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteRole(row.id)
          this.$message.success('删除成功')
          this.getRoleList()
        } catch (error) {
          this.$message.error('删除失败')
        }
      })
    },

    // 批量删除
    handleBatchDelete() {
      const ids = this.selectedRoles.map(role => role.id)
      this.$confirm(`确定要删除选中的 ${ids.length} 个角色吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await batchDeleteRoles(ids)
          this.$message.success('批量删除成功')
          this.getRoleList()
        } catch (error) {
          this.$message.error('批量删除失败')
        }
      })
    },

    // 权限管理
    async handlePermissions(row) {
      this.currentRole = row
      this.permissionDialogVisible = true
      try {
        const response = await getRolePermissions(row.id)
        this.rolePermissions = response.data.map(p => p.id)
      } catch (error) {
        this.$message.error('获取角色权限失败')
      }
    },

    // 提交角色表单
    handleSubmit() {
      this.$refs.roleForm.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            if (this.isEdit) {
              await updateRole(this.roleForm.id, this.roleForm)
              this.$message.success('更新成功')
            } else {
              await createRole(this.roleForm)
              this.$message.success('创建成功')
            }
            this.dialogVisible = false
            this.getRoleList()
          } catch (error) {
            this.$message.error(this.isEdit ? '更新失败' : '创建失败')
          } finally {
            this.submitLoading = false
          }
        }
      })
    },

    // 提交权限设置
    async handlePermissionSubmit() {
      this.permissionLoading = true
      try {
        const checkedKeys = this.$refs.permissionTree.getCheckedKeys()
        const halfCheckedKeys = this.$refs.permissionTree.getHalfCheckedKeys()
        const permissionIds = [...checkedKeys, ...halfCheckedKeys]
        
        await updateRolePermissions(this.currentRole.id, permissionIds)
        this.$message.success('权限设置成功')
        this.permissionDialogVisible = false
        this.getRoleList()
      } catch (error) {
        this.$message.error('权限设置失败')
      } finally {
        this.permissionLoading = false
      }
    },

    // 获取权限列表
    async getPermissionList() {
      try {
        const response = await getPermissionList()
        this.permissionList = response.data || []
      } catch (error) {
        console.error('获取权限列表失败:', error)
      }
    },

    // 对话框关闭
    handleDialogClose() {
      this.$refs.roleForm.resetFields()
    },

    handlePermissionDialogClose() {
      this.currentRole = {}
      this.rolePermissions = []
    }
  }
}
</script>

<style scoped>
.roles-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-box {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin-bottom: 0;
}

.table-container {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.batch-actions {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  background: #fafafa;
}

.selected-info {
  margin-left: 10px;
  color: #909399;
  font-size: 14px;
}

.pagination-container {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

.permission-header {
  margin-bottom: 20px;
}

.permission-header h4 {
  margin: 0;
  color: #303133;
}

.permission-tree {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>